
from extra_service.kimi import *


DEFAULT_TOKEN = "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ1c2VyLWNlbnRlciIsImV4cCI6MTc0MDUzODg3NCwiaWF0IjoxNzMyNzYyODc0LCJqdGkiOiJjdDN0cHVtZ2kzcG0xcTVxMmkxZyIsInR5cCI6InJlZnJlc2giLCJhcHBfaWQiOiJraW1pIiwic3ViIjoiY3FtZ3V2dWNwN2YxaHJmOGNuMTAiLCJzcGFjZV9pZCI6ImNxbWd1dnVjcDdmMWhyZjhjbjBnIiwiYWJzdHJhY3RfdXNlcl9pZCI6ImNxbWd1dnVjcDdmMWhyZjhjbjAwIn0.RTgRE3KIY37tIRXpIOUPm4V_O4A1ybc43iJDbATpBnPWvClO9Qvv4HuEMYT9dUnQS09q_dlCjRKIimBKHnXAGw"

class SingleService:

    def __init__(self,ip:str,port:int,pdf_url:str,token:str=DEFAULT_TOKEN) -> None:
        self.pdf_url = pdf_url
        self.meta = ChatMetaData(
            refresh_token=token,
            use_conversation_id=True,
            use_search=False
        )
        self.meta.setKimiServer(ip,port)
        self.history = dict()
    
    def Pipline(self,texts_list:list[str]):
        lenth = len(texts_list)
        print(f"all lens: {lenth}")
        if lenth == 0:
            return None
        for idx, text in enumerate(texts_list):
            print(f"cur: {idx}")
            content = None
            if idx == 0:
                content = KimiDoc(self.meta).Chat(self.pdf_url,text)
            else:
                content = KimiChat(self.meta).Chat(text)
            self.history[idx] = {
                "conv_id": self.meta.conversation_id,
                "idx": idx,
                "text": text,
                "content": content,
            }
            if content is None:
                raise Exception(f"content is None on idx {idx}")
        return self.history
    
    def DumpToMd(self,file_path:str,title_list:list[str]=None):
        keys = self.history.keys()
        keys = sorted(keys)
        use_title = title_list is not None
        use_title = use_title and len(title_list) == len(keys)
        with open(file_path,"w",encoding="utf-8") as fp:
            for idx in keys:
                content = self.history[idx]["content"]
                if isinstance(content,str):
                    if use_title:
                        fp.write(title_list[idx] + "\n\n")
                    fp.write(content + "\n\n")
            fp.close()



GLOBAL_PROMPT_LIST = []
GLOBAL_TITLE_LIST = None
GLOBAL_PDF_URL = ""
GLOBAL_TOKEN = None

def SinglePdfRun(md_file_path:str):
    global GLOBAL_TOKEN,GLOBAL_PROMPT_LIST
    global GLOBAL_TITLE_LIST,GLOBAL_PDF_URL

    if GLOBAL_TOKEN is None:
        GLOBAL_TOKEN = DEFAULT_TOKEN
    print(GLOBAL_PDF_URL)
    ss = SingleService(
        "81.70.84.40",
        8000,
        GLOBAL_PDF_URL,
        GLOBAL_TOKEN
    )
    history = ss.Pipline(GLOBAL_PROMPT_LIST)
    ss.DumpToMd(md_file_path,GLOBAL_TITLE_LIST)
    return history

